package com.credithc.signature.manager.utils;

import com.credithc.baseserv.core.utils.UUIDUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.ImageType;
import org.apache.pdfbox.rendering.PDFRenderer;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @desc: <br/>
 * @author: Jingbo Hu<br/>
 * @time：2020年05⽉29⽇<br/>
 * @version：v1.0.0<br>
 */
public class PdfToImageUtil {

    private static final String DEFAULT_FORMAT_NAME = "png";
    private static final Float DEFAULT_FLOAT_DPI = 150F;


    /**
     * PDF转一张图片
     *
     * @param sourcePath
     * @param destPath
     */
    public static void transformOne(String sourcePath, String destPath, float dpi, String formatName) {
        try {
            if (dpi == 0) {
                dpi = DEFAULT_FLOAT_DPI;
            }
            if (StringUtils.isEmpty(formatName)) {
                formatName = DEFAULT_FORMAT_NAME;
            }

            FileInputStream fileIo = new FileInputStream(sourcePath);
            PDDocument pdDocument = PDDocument.load(fileIo);
            int pages = pdDocument.getNumberOfPages();

            // 总高度
            int height = 0;
            // 总宽度
            int width = 0;
            // 临时的高度 , 或保存偏移高度
            int tempHeight = 0;
            // 临时的高度，主要保存每个高度
            int tempHeight2 = 0;
            // 图片的数量
            // 保存每个文件的高度
            int[] heightArray = new int[pages];
            // 保存所有的图片的RGB
            List<int[]> imageRgb = new ArrayList<>();
            // 保存一张图片中的RGB数据
            int[] tempRgb;
            BufferedImage bufferedImage = null;
            for (int i = 0; i < pages; i++) {
                bufferedImage = new PDFRenderer(pdDocument).renderImageWithDPI(i, dpi, ImageType.RGB);
                // 图片高度
                heightArray[i] = tempHeight = bufferedImage.getHeight();
                if (i == 0) {
                    // 图片宽度
                    width = bufferedImage.getWidth();
                }
                // 获取总高度
                height += tempHeight;
                // 从图片中读取RGB
                tempRgb = new int[width * tempHeight];
                tempRgb = bufferedImage.getRGB(0, 0, width, tempHeight, tempRgb, 0, width);
                imageRgb.add(tempRgb);
            }
            // 设置偏移高度为0
            tempHeight = 0;
            // 生成新图片
            BufferedImage imageResult = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            for (int i = 0; i < pages; i++) {
                tempHeight2 = heightArray[i];
                if (i != 0) {
                    // 计算偏移高度
                    tempHeight += tempHeight2;
                }
                // 写入流中
                imageResult.setRGB(0, tempHeight, width, tempHeight2, imageRgb.get(i), 0, width);
            }
            // 写图片
            ImageIO.write(imageResult, formatName, new File(destPath));
            pdDocument.close();
            fileIo.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * PDF转多张张图片
     * DPI越大，转换效率越低
     * 需要目标文件的目录存在
     * @param sourcePath
     * @param dpi
     * @param formatName
     */
    public static void transformMore(String sourcePath, String destPath, float dpi, String formatName) throws IOException {
        if (dpi == 0) {
            dpi = DEFAULT_FLOAT_DPI;
        }
        if (StringUtils.isEmpty(formatName)) {
            formatName = DEFAULT_FORMAT_NAME;
        }

        File file = new File(sourcePath);
        PDDocument pdDocument;
        try {
            //图片目录
            pdDocument = PDDocument.load(file);
            int pages = pdDocument.getNumberOfPages();
            PDFRenderer renderer = new PDFRenderer(pdDocument);
            BufferedImage image = null;
            new File(destPath).mkdir();
            for (int i = 0; i < pages; i++) {
                //转换后的img目录
                String imgPath = destPath + File.separator + UUIDUtils.getUUID() + ".png";
                image = renderer.renderImageWithDPI(i, dpi);
                ImageIO.write(image, formatName, new File(imgPath));
            }
            pdDocument.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 测试
     * @param args
     * @throws IOException
     */
    public static void main(String[] args) throws IOException {
        String source = "D:/downloadFile.pdf";
        String dest = "D:/123";
        transformMore(source,dest,0,"");
    }
}
